package leetcode

func longestPalindromeMethod1(s string) string {
	start, maxLength := 0, 1
	n := len(s)

	if n < 2 {
		return s
	}

	if n < 3 && s[0] == s[1] {
		return s
	}

	if n < 4 && s[0] == s[1] {
		if s[1] != s[2] {
			return s[0:2]
		}
	}

	for i := 1; i < n-1; i++ {
		isPalindrome := false
		left, right := 0, 0
		if s[i+1] == s[i] {
			isPalindrome = true
			left = i
			right = i + 1
		}

		for isPalindrome && left > 0 && right < n-1 {
			left--
			right++
			if s[left] == s[right] {
				if left == 0 || right == n {
					break
				}
				continue
			}
			isPalindrome = false
			left++
			right--
			break
		}

		if right-left+1 > maxLength {
			start = left
			maxLength = right - left + 1
		}

		if s[i+1] == s[i-1] {
			isPalindrome = true
			left = i - 1
			right = i + 1
		}

		for isPalindrome && left > 0 && right < n-1 {
			left--
			right++
			if s[left] == s[right] {
				if left == 0 || right == n {
					break
				}
				continue
			}
			isPalindrome = false
			left++
			right--
			break
		}

		if right-left+1 > maxLength {
			start = left
			maxLength = right - left + 1
		}
	}
	return s[start : start+maxLength]
}
